<template>
  <div ref="target" class="chart"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from "vue";
import * as echarts from "echarts";

interface DataItem {
  date: string[];
  data: Array<{ [key: string]: number }>;
}

const props = defineProps<{
  data: DataItem;
}>();

let chart: echarts.ECharts | null = null;
const target = ref<HTMLElement | null>(null);

const ChartInit = () => {
  if (!target.value || !props.data.date || !props.data.data) return;

  if (chart) {
    chart.dispose();
    chart = null;
  }

  const newSeries = Object.keys(props.data.data[0]).map((val) => ({
    name: val,
    type: "line",
    stack: "Total",
    data: props.data.data.map((item) => item[val]),
  }));
  const newLegendData = Object.keys(props.data.data[0]).map((item) => item);

  const option = {
    title: {
      text: "产品过去7天销量",
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: newLegendData,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    toolbox: {
      feature: {
        saveAsImage: {},
      },
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: props.data.date,
    },
    yAxis: {
      type: "value",
    },
    series: newSeries,
  };

  try {
    chart = echarts.init(target.value);
    chart.setOption(option);
  } catch (error) {
    console.error("Error setting option:", error);
  }
};

const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

let resizeObserver: ResizeObserver | null = null;

onMounted(() => {
  ChartInit();
  resizeObserver = new ResizeObserver(handleResize);
  if (target.value) {
    resizeObserver.observe(target.value);
  }
});

onUnmounted(() => {
  if (resizeObserver && target.value) {
    resizeObserver.unobserve(target.value);
    resizeObserver.disconnect();
  }
  if (chart) {
    chart.dispose();
    chart = null;
  }
});

watch(() => props.data, ChartInit);
</script>

<style lang="less" scoped>
.chart {
  height: 300px;
  width: 100%;
  margin-right: 50px;
}
</style>